package models

import (
	"CRMSystem/utils"
	"errors"
	"fmt"
	"github.com/beego/beego/v2/adapter/orm"
)

// FormData 用户表单

type FormData struct {
	Password    string `json:"password"`
	RePassword  string `json:"rePassword"`
	PhoneNumber string `json:"phone"`
}

// Users 用户
type Users struct {
	Id        int    `orm:"column(user_ID)"`
	UserName  string `orm:"column(user_name)"`
	Password  string `orm:"column(password)"`
	ContactId int    `orm:"column(contact_ID)"`
}

func init() {
	orm.RegisterModel(new(Users))
}

// AddUser 添加用户
func AddUser(u Users) int64 {
	o := orm.NewOrm()
	insert, err := o.Insert(&u)
	if err != nil {
		return -1
	}
	return insert
}

// SelectByUsernamePassword 按用户名密码查询
func SelectByUsernamePassword(u Users) bool {
	username := u.UserName
	user := Users{UserName: username}
	o := orm.NewOrm()
	err := o.Read(&user, "UserName")
	if errors.Is(err, orm.ErrNoRows) {
		fmt.Println("查询不到")
	} else if errors.Is(err, orm.ErrMissPK) {
		fmt.Println("找不到主键")
	}
	if u.Password == user.Password {
		return true
	}
	return false
}

// SelectContactIDByUserName 根据用户名找
func SelectContactIDByUserName(username string) int {
	user := Users{UserName: username}
	o := orm.NewOrm()
	err := o.Read(&user, "UserName")
	if errors.Is(err, orm.ErrNoRows) {
		fmt.Println("查询不到")
	} else if errors.Is(err, orm.ErrMissPK) {
		fmt.Println("找不到主键")
	}
	return user.ContactId
}

// ChangePassword 修改密码
func ChangePassword(username, password string) error {
	o := orm.NewOrm()
	err := o.Begin()
	passwordHash := utils.SHA256(password)
	_, err = o.Raw("update users set password = ? where user_name = ?", passwordHash, username).Exec()
	if err != nil {
		err = o.Rollback()
		return err
	} else {
		err = o.Commit()
		return nil
	}
}
